package de.ttf.ts.test;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import de.ttf.ts.model.Club;
import de.ttf.ts.model.Player;

public class Fixtures implements Fixture {

    private SimpleJdbcTemplate jdbcTemplate;

    @PersistenceContext
    private EntityManager em;

    @Value("${hhh.dialect}")
    String dbDialect;

    @SuppressWarnings("unchecked")
    @Override
    public void init() throws Exception {
        if (dbDialect == null || dbDialect.contains("H2")) {

        }

        /*
        if (!getBoolean("noTestdata")) {
            ScriptEngine groovy = new ScriptEngineManager().getEngineByName("groovy");
            Bindings bindings = groovy.getBindings(ScriptContext.ENGINE_SCOPE);
            groovy.eval(IOUtils.toString(getClass().getResourceAsStream("/testdata_common.groovy"), "UTF-8"));
            groovy.eval(IOUtils.toString(getClass().getResourceAsStream("/testdata.groovy"), "UTF-8"));
            List<Object> entities = new ArrayList<Object>();
            entities.addAll(bindings.values());
            entities.addAll((Collection<Object>) bindings.get("persist"));
            persistObjects(entities);
            em.flush();
        }
        */
    }

    private static Class<?>[] persistClassOrder = new Class[] { Player.class, Club.class };

    private void persistObjects(Collection<Object> objects) {
        for (Class<?> clazz : persistClassOrder) {
            for (Object object : objects) {
                if (object.getClass() == clazz) {
                    try {
                        em.persist(object);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    private String getConstrName(String tableName, String column) {
        String sql = "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE CONSTRAINT_TYPE = 'REFERENTIAL' AND  TABLE_NAME = '%s' AND COLUMN_LIST = '%s'";
        return jdbcTemplate.queryForObject(String.format(sql, tableName, column), String.class);
    }

    private void dropConstraint(String tableName, String constraintName) {
        jdbcTemplate.update(String.format("ALTER TABLE %s DROP CONSTRAINT %s", tableName, constraintName));
    }

    private void createConstraint(String table, String name, String foreignKey, String references) {
        jdbcTemplate.update(String.format(
                "alter table %s add constraint %s foreign key (%s) references %s ON DELETE CASCADE", table, name,
                foreignKey, references));
    }

    public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

}
